import request from 'request'
import { BASEURL } from '../config/api.json'

class RequestUtil {
    constructor() {
    }

    get(url, queryParams) {
        const options = {
            uri: this.getUrl(url, queryParams),
            method: 'GET'
        }
        return this.sendRequest(options);
    }

    delete(url, queryParams) {
        const options = {
            uri: this.getUrl(url, queryParams),
            method: 'DELETE'
        }
        return this.sendRequest(options);
    }

    post(url, queryParams, data = {}) {
        const options = {
            uri: this.getUrl(url, queryParams),
            method: 'POST',
            json: data
        }
        return this.sendRequest(options);
    }

    put(url, queryParams, data = {}) {
        const options = {
            uri: this.getUrl(url, queryParams),
            method: 'PUT',
            json: data
        }
        return this.sendRequest(options);
    }

    sendRequest(options = {}) {
        options.timeout = 8000;
        return new Promise((resolve, reject) => {
            request(options, (error, response, body) => {
                const result = {
                    response: response,
                    body: body,
                    error: error
                }
                if (!error && (response.statusCode == 200)) {
                    resolve(result);
                } else {
                    reject(error);
                }
            })
        });
    }

    getUrl(url, queryParams) {
        if (!queryParams) return BASEURL + url;
        let queryString = '';
        for (let qp in queryParams) {
            const pathVariable = `{${qp}}`
            if (url.indexOf(pathVariable) > -1) {
                url = url.replace(new RegExp(pathVariable, 'gm'), queryParams[qp]);
            } else {
                queryString += `${qp}=${queryParams[qp]}`;
            }
        }
        return !!queryString ? `${BASEURL}${url}?${queryString}` : BASEURL + url;
    }

    getKong(url, queryParams) {
        const options = {
            uri: this.getKongUrl(url, queryParams),
            method: 'GET'
        }
        return this.sendKongRequest(options);
    }

    deleteKong(url, queryParams) {
        const options = {
            uri: this.getKongUrl(url, queryParams),
            method: 'DELETE',
            operation: 'delete api '
        }
        return this.sendKongRequest(options);
    }

    putKong(url, queryParams, data = {}) {
        const options = {
            uri: this.getKongUrl(url, queryParams),
            method: 'PUT',
            json: data
        }
        return this.sendKongRequest(options);
    }

    // kong 0.9.9
    // addKongApi(url, queryParams, data={}){
    //     const kongData = {
    //         name: data.name,
    //         request_path: data.request_path,
    //         upstream_url: data.upstream_url
    //     }
    //     const options = {
    //         uri : this.getKongUrl(url, queryParams),
    //         method : 'POST',
    //         json : kongData,
    //         kongUrl: data.kongUrl
    //     }
    //     return this.sendKongRequest(options);
    // }


    //ClownMonkey test
    postPreheating(url, queryParams, data = {},ip) {
        console.log("postPreheating" + data.perload_redis_host);
        const options = {
            uri: this.getPreheatingUrl(url, queryParams,ip),
            method: 'GET',
            // method: 'POST',
            json: data
        }
        return this.sendRequest(options);
    }
    getPreheatingUrl(url, queryParams,ip) {
        let BASEPREHEATINGURL = `http://${ip}:8001`;
        console.log(`${BASEPREHEATINGURL}`);
        console.log(BASEPREHEATINGURL + url);
        return BASEPREHEATINGURL + url;
    }



    // kong 0.10.2
    addKongApi(url, queryParams, data = {}) {
        const kongData = {
            name: data.name,
            uris: data.request_path,
            upstream_url: data.upstream_url,
            strip_uri: false
        }
        const options = {
            uri: this.getKongUrl(url, queryParams),
            method: 'POST',
            json: kongData,
            kongUrl: data.kongUrl,
            accesspointUrl: data.accesspointUrl,
            operation: 'register api'
        }
        return this.sendKongRequest(options);
    }

    getKongUrl(url, queryParams) {
        if (!queryParams) return url;
        let queryString = '';
        for (let qp in queryParams) {
            const pathVariable = `{${qp}}`
            if (url.indexOf(pathVariable) > -1) {
                url = url.replace(new RegExp(pathVariable, 'gm'), queryParams[qp]);
            } else {
                queryString += `${qp}=${queryParams[qp]}`;
            }
        }
        return !!queryString ? `${url}?${queryString}` : url;
    }

    sendKongRequest(options = {}) {
        options.timeout = 8000;
        return new Promise((resolve, reject) => {
            request(options, (error, response, body) => {
                const result = {
                    response: response,
                    body: body,
                    error: error
                }
                if (!error && (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204 || response.statusCode == 409)) {
                    // resolve(`${options.kongUrl} ${options.operation} success; `);
                    console.log(`${options.kongUrl} ${options.operation} success; `);
                    resolve();
                } else {
                    reject(`error: kong-${options.kongUrl} accesspoint-${options.accesspointUrl} ${options.operation} msg: ${error}; `);
                }
            })
        });
    }

}

export default RequestUtil;




